package com.zrrd.gmall.order.controller;

import com.zrrd.gmall.cart.fegin.CartFeginClient;
import com.zrrd.gmall.common.result.Result;
import com.zrrd.gmall.common.util.AuthContextHolder;
import com.zrrd.gmall.model.cart.CartInfo;
import com.zrrd.gmall.model.order.OrderDetail;
import com.zrrd.gmall.model.order.OrderInfo;
import com.zrrd.gmall.model.user.UserAddress;
import com.zrrd.gmall.order.service.OrderService;
import com.zrrd.gmall.product.fegin.ProductFeginClient;
import com.zrrd.gmall.user.fegin.UserFeginClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private UserFeginClient userFeginClient;
    @Autowired
    private CartFeginClient cartFeginClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductFeginClient productFeginClient;

    //确认订单（结算）
    @GetMapping("/auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request) {
        //获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        //获取用户地址
        List<UserAddress> userAddressList = userFeginClient.findUserAddressByUserId(userId);
        //获取用户选中的购物车商品
        List<CartInfo> cartCheckedList = cartFeginClient.getCartCheckedList(userId);
        //创建一个订单明细集合
        List<OrderDetail> detailList = new ArrayList<>();
        //遍历获取的购物车集合
        for (CartInfo cartInfo : cartCheckedList) {
            //创建订单明细对象
            OrderDetail detail = new OrderDetail();
            detail.setSkuId(cartInfo.getSkuId());
            detail.setSkuName(cartInfo.getSkuName());
            detail.setSkuNum(cartInfo.getSkuNum());
            detail.setImgUrl(cartInfo.getImgUrl());
            detail.setOrderPrice(cartInfo.getSkuPrice());
            //添加到集合
            detailList.add(detail);
        }

        //计算总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailList);
        orderInfo.sumTotalAmount();


        //创建一个最终返回的Map集合
        Map<String, Object> map = new HashMap<>();
        map.put("userAddressList", userAddressList);
        map.put("detailArrayList", detailList);
        map.put("totalNum", detailList.size());
        map.put("totalAmount", orderInfo.getTotalAmount());
        //存入生成的流水号
        String tradeNo = orderService.getTradeNo(userId);
        map.put("tradeNo", tradeNo);

        //返回结果
        return Result.ok(map);

    }

    //提交订单（下单）
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        //设置用户ID
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //获取前端传递过来的流水号
        String tradeNo = request.getParameter("tradeNo");
        //比较流水号
        if (!orderService.checkTradeNo(userId, tradeNo)) {
            return Result.fail().message("不能重复提交订单！");
        }
        //删除流水号
        orderService.deleteTradeNo(userId);

        //获取订单明细集合
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail detail : orderDetailList) {
            //验证库存
            boolean b = orderService.checkStock(detail.getSkuId(), detail.getSkuNum());
            if (!b) {
                return Result.fail().message(detail.getSkuName() + "库存不足!");
            }
            //验证价格
            BigDecimal skuPrice = productFeginClient.getSkuPrice(detail.getSkuId());
            if (detail.getOrderPrice().compareTo(skuPrice) != 0) {
                //重新加载一次最新价格
                cartFeginClient.loadCartCache(userId);
                return Result.fail().message(detail.getSkuName() + "价格有变动！");
            }
        }

        //执行保存订单
        Long orderId = orderService.saveOrderInfo(orderInfo);
        //返回订单ID
        return Result.ok(orderId);
    }

    //获取订单信息（包含了订单明细 给支付服务提供数据）
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable("orderId") Long orderId){
        return orderService.getOrderInfo(orderId);
    }
}
